
package com.netease.xone.fragment;

import java.util.Timer;
import java.util.TimerTask;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.User;
import Utils.XoneUtil;
import android.app.Service;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.pkgRelated.XoneConsts.INPUT_CELLPHONE_TYPE;
import com.netease.xone.R;
import com.netease.xone.app.XoneApp;
import com.netease.xone.widget.CustomDialog.OnCustomDlgCancelListener;
import com.netease.xone.widget.EditTextWithClear;

public class FragCellPhoneLogin extends FragCellPhoneBase {

    private EditText mCellphoneNumEdit;
    private EditText mPwEdit;
    private Button mLoginBtn;
    private FragmentManager mFragmentManager;
    private int mLoginTransId;

    @SuppressWarnings("deprecation")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        NTLog.i("FragCellPhoneLogin", "onCreateView");
        setHasOptionsMenu(true);
        mFragmentManager = getFragmentManager();
        getActivity().setTitle(R.string.cellphoneLogin);
        String phoneNum = null;// TODO: 从数据库读取上次登录的手机号
        View view = inflater.inflate(R.layout.fragment_cellphone_login, container, false);
        mCellphoneNumEdit = (EditTextWithClear)view.findViewById(R.id.cellphoneLoginAccount);
        mPwEdit = (EditTextWithClear)view.findViewById(R.id.cellphoneLoginPassword);
        if (phoneNum != null) {
            mCellphoneNumEdit.setText(phoneNum);
        }

        mPwEdit.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_ENTER) && event.getAction() == KeyEvent.ACTION_UP) {
                    doLogin();
                    return true;
                }
                return false;
            }
        });

        mLoginBtn = (Button)view.findViewById(R.id.cellphoneLoginBtn);
//        StateListDrawable stateListDrawable = new StateListDrawable();
//        stateListDrawable.addState(new int[] {
//            android.R.attr.state_pressed
//        }, getResources().getDrawable(R.drawable.btn_red_prs));
//        stateListDrawable.addState(new int[] {}, getResources().getDrawable(R.drawable.btn_red));
//        mLoginBtn.setBackgroundDrawable(stateListDrawable);
        mLoginBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doLogin();
            }
        });

        Button registerBtn = (Button)view.findViewById(R.id.cellphoneRegisterBtn);
        registerBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Fragment frag = FragCellPhoneInputNum.newInstance(INPUT_CELLPHONE_TYPE.Register);
                mFragmentManager.beginTransaction()
                        .replace(R.id.activity_CellPhone_container_id, frag).addToBackStack(null)
                        .commit();
            }
        });

        TextView forgotPassword = (TextView)view.findViewById(R.id.cellphoneLoginForgotPassword);
        SpannableString ss = new SpannableString(getString(R.string.forgetPassword));
        ss.setSpan(new UnderlineSpan(), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        forgotPassword.setText(ss);
        forgotPassword.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Fragment frag = FragCellPhoneInputNum.newInstance(INPUT_CELLPHONE_TYPE.FindPw);
                mFragmentManager.beginTransaction()
                        .replace(R.id.activity_CellPhone_container_id, frag).addToBackStack(null)
                        .commit();
            }
        });
        return view;
    }

    private void doLogin() {
        String phoneNum = mCellphoneNumEdit.getText().toString().trim();
        String passwordStr = mPwEdit.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            showToast(R.string.inputPhoneNumberHint);
            return;
        } else if (TextUtils.isEmpty(passwordStr)) {
            showToast(R.string.input_password);
            return;
        } else if (!XoneUtil.isValidatePhoneNum(phoneNum)) {
            showToast(R.string.phoneNumInvalid);
            return;
        }
//      showWatting(getString(R.string.logining));
        showCustomDialog(getActivity(), getString(R.string.logining), mOnCustomDlgCancelListener);
        XoneService.getInstance().addListener(mXoneCallBack);
        mLoginTransId = XoneService.getInstance().doLogin(XoneConsts.ACCOUNT_TYPE.Phone,
                phoneNum, passwordStr);
    }
    @Override
    public void onStart() {
        super.onStart();
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                if (getActivity() != null) {
                    InputMethodManager imm = (InputMethodManager)XoneApp.getAppInstance()
                            .getSystemService(Service.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(mCellphoneNumEdit, 0);
                }
            }
        }, 300);
        mCellphoneNumEdit.requestFocus();
    }
    private OnCustomDlgCancelListener mOnCustomDlgCancelListener = new OnCustomDlgCancelListener(){

        @Override
        public void onCancel() {
            XoneService.getInstance().cancelTransaction(mLoginTransId);
        }  
    };
    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);
    }
    
    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLogin(int transactionId, User account) {
//            stopWaiting();
            closeCustomDialog();
            XoneService.getInstance().removeListener(mXoneCallBack);
            getActivity().finish();
        }

        @Override
        public void onLoginError(int transactionId, int errCode, String err) {
            if (mLoginTransId == transactionId) {
//                stopWaiting();
                closeCustomDialog();
                XoneService.getInstance().removeListener(mXoneCallBack);
                if (XoneServiceCode.LOGINREG_ERR_XONE_USERNONE == errCode) {
                    showToast(R.string.user_not_reg);
                } else {
                    showToast(err);
                }
            }
        }
    };
}
